package smscommon.sms;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

import smscommon.ComFun;
import smsmessage.ACTIVETEST;
import smsmessage.EXT;
import smsmessage.sms.SUBMIT;

public class SmsSendMsgThread1 extends Thread {

	public static void main(String[] args) {
		SmsSendMsgThread1 smsSendMsgThread1 = new SmsSendMsgThread1(1,
				"127.0.0.1", 15000, "000001", "000001");

		smsSendMsgThread1.run();

	}

	private static Logger logger = Logger.getLogger(SmsSendMsgThread1.class);
	private ResourceBundle pro;
	private String USERNAME;
	private String PASSWORD;
	private String default_submitSleep;
	private String default_poolNum;
	private String ACTIVETEST_INTERVAL;
	private int startCheckMsg;
	private int threadID;
	private String ip;
	private int port;
	private Connect conn;
	private SmsPool msgPool;
	private PowerFlag powerFlag;
	private Queue queue;
	private long m_activeTestTime;
	private static int sendIndex = 1;

	public SmsSendMsgThread1(int threadID, String ip, int port,
			String userName, String passwd) {
		pro = null;
		default_submitSleep = "0";
		default_poolNum = "500";
		ACTIVETEST_INTERVAL = "30";
		startCheckMsg = 100;
		conn = Connect.getInstance();
		msgPool = SmsPool.getInstance();
		powerFlag = PowerFlag.getInstance();
		queue = Queue.getInstance();
		this.threadID = threadID;
		this.ip = ip;
		this.port = port;
		USERNAME = userName;
		PASSWORD = passwd;
		try {
			pro = ResourceBundle.getBundle("diy09SMS");
			ACTIVETEST_INTERVAL = pro.getString("ACTIVETEST_INTERVAL");
			default_submitSleep = pro.getString("default_submitSleep");
			default_poolNum = pro.getString("default_poolNum");
		} catch (Exception e) {
			logger.info((new StringBuilder("The API's property was not found!!"))
					.append(e).toString());
		}
	}

	public void run() {
		SocketChannel channel = null;
		int containCount = 500;
		try {
			containCount = Integer.parseInt(default_poolNum);
		} catch (Exception e) {
			logger.info((new StringBuilder("The API's property was not found!!"))
					.append(e).toString());
		}
		int i = 0;
		while (powerFlag.getFlag() == 0) {
			try {
				switch (Connect.status[threadID]) {
				case 1: // '\001'
				default:
					break;

				case 0: // '\0'
					logger.debug("**********start connect*****************");
					synchronized (conn) {
						channel = conn.getConn(threadID, ip, port, USERNAME,
								PASSWORD);
					}
					break;

				case 2: // '\002'
					logger.debug("***************start send Msg***************");
					sendMsg(channel, containCount);
					sendResp(channel);
					sendTestPack(channel);
					break;

				case 3: // '\003'
					conn.closeConn(threadID);
					powerFlag.setFlag(1);
					break;
				}
			} catch (Exception e) {
				logger.error(this, e);
			}
		}
		if (powerFlag.getFlag() == 1) {
			logger.error("*************bind failure for SMS's usename and passwd was wrong or by you stop."
					+ "!!!!! *****");
		} else if (powerFlag.getFlag() == 2) {
			logger.debug("************sms stop conn***************");
			powerFlag.setConnFlag(1);
			Connect.status[threadID] = 0;
			conn.closeConn(threadID);
		}
	}

	private void sendMsg(SocketChannel channel, int containCount) {
		try {
			SUBMIT mt = new SUBMIT();
			if ((mt = msgPool.removeSUBMIT()) != null) {
				if (!"".equals(default_submitSleep)
						&& !"0".equals(default_submitSleep)) {
					sleep(Integer.parseInt(default_submitSleep));
				}
				ByteBuffer bb = null;
				bb = mt.toByteBuffer();
				int nbytes = 0;
				nbytes = channel.write(bb);
				logger.debug((new StringBuilder(
						"&&&&&&&&&&&&&&&&&&&&&&&&&&submit\u53D1\u9001:{"))
						.append(sendIndex++).append("}").toString());
				if (nbytes != bb.capacity()) {
					powerFlag.setConnFlag(1);
					Connect.status[threadID] = 0;
					logger.error("******************send sms was wrong!!*********************");
				} else {
					switch (mt.head.commandid) {
					case 3: // '\003'
						logger.debug((new StringBuilder(
								"submit success nbytes=")).append(nbytes)
								.append(" ").append(mt).toString());
						break;
					}
				}
			} else {
				Thread.sleep(1000L);
			}
		} catch (Exception e1) {
			powerFlag.setConnFlag(1);
			Connect.status[threadID] = 0;
			logger.error(e1);
		}
	}

	private void sendResp(SocketChannel channel) {
		ByteBuffer bb = null;
		EXT ext;
		try {
			if ((ext = msgPool.removeEXT()) != null) {
				logger.debug("\u4E0B\u884Cresp");
				bb = ext.getBb();
				int nbytes = channel.write(bb);
				if (nbytes != bb.capacity()) {
					logger.error((new StringBuilder(
							"\u53D1\u9001\u68C0\u6D4B\u5305\u5931\u8D25 nbytes="))
							.append(nbytes).toString());
					powerFlag.setConnFlag(1);
					Connect.status[threadID] = 0;
				} else {
					logger.debug(ComFun.getCommandid(ext.head.commandid));
				}
			}
		} catch (IOException e) {
			logger.error(e);
		}
	}

	private void sendTestPack(SocketChannel channel) {
		ByteBuffer bb = null;
		try {
			int activeTestInterval = Integer.parseInt(ACTIVETEST_INTERVAL);
			if (activeTestInterval <= 2) {
				activeTestInterval = 2;
			}
			if (System.currentTimeMillis() - m_activeTestTime >= (long) (activeTestInterval * 1000)) {
				m_activeTestTime = System.currentTimeMillis();
				ACTIVETEST aCTIVETEST = new ACTIVETEST();
				bb = aCTIVETEST.getNextActiveTest();
				int nbytes = channel.write(bb);
				if (nbytes != bb.capacity()) {
					logger.debug("Send ActiveTest failure!");
					powerFlag.setConnFlag(1);
					Connect.status[threadID] = 0;
				} else {
					logger.debug("Send ActiveTest success.");
				}
			}
		} catch (IOException e) {
			logger.error(e);
		}
	}

}
